//
//  BDAddrMyViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/1.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDAddrMyViewController.h"
#import "BDAddrAddTableTableViewController.h"
#import "BDAddrListTableViewCell.h"

#import "BDNavigationController.h"
#import "BDLoginTableViewController.h"

#define hideHeight 37.0;

@interface BDAddrMyViewController () <UITableViewDelegate,UITableViewDataSource>
{
    CGFloat _hideHeight;
    NSArray *_addrList;
    
    NSDictionary *_addrDic;
    BOOL isEdit;
    BOOL presentLoginView;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *addAddrButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBottomSpace;
@property (weak, nonatomic) IBOutlet UIButton *navgationBarButton;


@end

@implementation BDAddrMyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"收货地址";
    _hideHeight = hideHeight;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self reloadData:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender {
    NSString *url = [NSString stringWithFormat:@"%@%@?userId=%@",[BDNetworking shareInstance].baseUrl,Addr_Query,[BDAccountManagerModel shareInstance].userId];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"获取地址失败:%@",error);
            if ([[error localizedDescription] isEqualToString:@"登录超时"] && error.code == 401) {
                [MBProgressHUD showToast:self.view withText:@"登录超时，请重新登录"];
                if (!presentLoginView) {
                    presentLoginView = YES;
                    // 清除webViw cookie
                    NSHTTPCookie *cookie;
                    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                    for (cookie in [storage cookies])
                    {
                        [storage deleteCookie:cookie];
                    }
                    
                    [BDAccountManagerModel shareInstance].authorization = @"";
                    [BDAccountManagerModel shareInstance].login = NO;
                    UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                    BDNavigationController *nav_addrVc = [stroyboard instantiateViewControllerWithIdentifier:@"navLoginStoryboardID"];
                    [self presentViewController:nav_addrVc animated:YES completion:nil];
                }
            } else {
                [MBProgressHUD showToast:self.view withText:@"获取地址失败"];
            }
        } else {
            NSLog(@"result = %@",results);
            _addrList = (NSArray *)results;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (_addrList.count == 0) {
                    _tableViewBottomSpace.constant = 0;
                    _navgationBarButton.hidden = YES;
                    _addAddrButton.hidden = YES;
                } else {
                    _tableViewBottomSpace.constant = 50;
                    _navgationBarButton.hidden = NO;
                    _addAddrButton.hidden = NO;
                }
                
                [self.tableView reloadData];
            });
            
        }
    }];
}

- (void)deleteAddr:(NSInteger) addrId {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@"正在删除"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@?id=%ld",[BDNetworking shareInstance].baseUrl,Addr_Delete,(long)addrId];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"DELETE" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"删除地址失败:%@",error);
            hud.labelText = @"删除地址失败";
            [hud hideAfterDelay:0.5];
        } else {
            [hud hideAfterDelay:0.5];
            NSLog(@"result = %@",results);
            [self reloadData:nil];
        }
    }];
}

- (void)setDefaultAddr:(NSInteger) addrId {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@"正在设为默认地址"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@?id=%ld",[BDNetworking shareInstance].baseUrl,Addr_Default,(long)addrId];
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"PUT" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        if (error != nil) {
            NSLog(@"设置默认地址失败:%@",error);
            hud.labelText = @"设置默认地址失败";
            [hud hideAfterDelay:0.5];
        } else {
            [hud hideAfterDelay:0.5];
            NSLog(@"result = %@",results);
            [self reloadData:nil];
        }
    }];
}

#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    tableView.scrollEnabled = _addrList.count > 0 ? YES : NO;
    return _addrList.count > 0 ? _addrList.count : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_addrList.count > 0) {
        static NSString *cellStr = @"addrCell";
        BDAddrListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        NSDictionary *addrDic = (NSDictionary *)_addrList[indexPath.row];
        
        for (NSUInteger i = 104; i < 107; i++) {
            if (_hideHeight > 0) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[cell viewWithTag:i] setHidden:YES];
                    cell.textViewBottomSpace.constant = 5.0;
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[cell viewWithTag:i] setHidden:NO];
                    cell.textViewBottomSpace.constant = 43.0;
                });
            }
        }
        
        UILabel *nameLabel = (UILabel *)[cell viewWithTag:101];
        if (![addrDic[@"receiver"] isEqual:[NSNull null]]) {
            nameLabel.text = _addrList[indexPath.row][@"receiver"];
        } else {
            nameLabel.text = @"未知";
        }
        UILabel *phoneLabel = (UILabel *)[cell viewWithTag:102];
        if (![addrDic[@"telephone"] isEqual:[NSNull null]]) {
            NSString *telephone = addrDic[@"telephone"];
            if ([telephone isVaildEmail]) {
                phoneLabel.text = [NSString stringWithFormat:@"邮箱：%@",_addrList[indexPath.row][@"telephone"]];

            } else {
                phoneLabel.text = [NSString stringWithFormat:@"电话：%@",_addrList[indexPath.row][@"telephone"]];
            }
        } else {
            phoneLabel.text = [NSString stringWithFormat:@"电话：未知"];
        }
        UITextView *aadrTextView = (UITextView *)[cell viewWithTag:103];
        if (![addrDic[@"region"] isEqual:[NSNull null]] &&
            ![addrDic[@"detailAddress"] isEqual:[NSNull null]]) {
            if (![addrDic[@"defaultAddress"] isEqual:[NSNull null]]) {
                if ([addrDic[@"defaultAddress"] integerValue] == 1) {
                    NSString *str = [NSString stringWithFormat:@"【默认地址】%@%@",_addrList[indexPath.row][@"region"],_addrList[indexPath.row][@"detailAddress"]];
                    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:str];
                    [attriStr addAttribute:NSForegroundColorAttributeName value:RGBColor(255, 66, 0) range:NSMakeRange(0, 6)];
                    [attriStr addAttribute:NSForegroundColorAttributeName value:RGBColor(206, 206, 206) range:NSMakeRange(6, attriStr.length - 6)];
                    [attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, attriStr.length)];
                    aadrTextView.attributedText = attriStr;
                } else {
                    aadrTextView.text = [NSString stringWithFormat:@"%@%@",_addrList[indexPath.row][@"region"],_addrList[indexPath.row][@"detailAddress"]];
                }
            }
        } else {
            aadrTextView.text = @"地址未知";
        }
        if (![addrDic[@"defaultAddress"] isEqual:[NSNull null]]) {
            if ([addrDic[@"defaultAddress"] integerValue] == 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[cell viewWithTag:104] setHidden:YES];
//                    UILabel *defaultLabel = (UILabel *)[cell viewWithTag:107];
//                    defaultLabel.text = @"【默认地址】";
                });
                
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (_hideHeight > 0) {
                        [[cell viewWithTag:104] setHidden:YES];
                    }
//                    UILabel *defaultLabel = (UILabel *)[cell viewWithTag:107];
//                    defaultLabel.text = @"";
                });
            }
        }
        return cell;
    } else {
        static NSString *cellStr = @"noaddrCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        return cell;
    }
    
}

#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_addrList.count > 0) {
        CGFloat textViewHeight = 37.0;
        NSDictionary *addrDic = (NSDictionary *)_addrList[indexPath.row];
        NSString *addr;
        if (![addrDic[@"region"] isEqual:[NSNull null]] &&
            ![addrDic[@"detailAddress"] isEqual:[NSNull null]]) {
            if (![addrDic[@"defaultAddress"] isEqual:[NSNull null]]) {
                if ([addrDic[@"defaultAddress"] integerValue] == 1) {
                    addr = [NSString stringWithFormat:@"【默认地址】%@%@",_addrList[indexPath.row][@"region"],_addrList[indexPath.row][@"detailAddress"]];
                } else {
                    addr = [NSString stringWithFormat:@"%@%@",_addrList[indexPath.row][@"region"],_addrList[indexPath.row][@"detailAddress"]];
                }
            }
            textViewHeight = [addr boundingHeightWithSize:CGSizeMake(kScreen_Width - 30.0, CGFLOAT_MAX) font:[UIFont systemFontOfSize:14.0] lineSpace:8.0] + 10;
            textViewHeight = textViewHeight < 37.0 ? 37.0 : textViewHeight;
        }
        NSLog(@"row = %ld height = %f",(long)indexPath.row,textViewHeight);
        return textViewHeight + 93.0 - _hideHeight;
    } else {
        return kScreen_Height - 44.0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.flag isEqualToString:@"clickable"] && _addrList.count > 0) {
        NSLog(@"%ld",(long)indexPath.row);
        NSDictionary *dic = _addrList[indexPath.row];
        NSString *json = [NSString DataTOjsonString:dic];
        self.block(json);
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (_addrList.count > 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
        view.backgroundColor = RGBColor(238, 238, 238);
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_addrList.count > 0) {
        return 10;
    }
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark IBActions

- (IBAction)editButtonPressed:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [sender setTitle:@"完成" forState:UIControlStateNormal];
        _hideHeight = 0;
    } else {
        [sender setTitle:@"编辑" forState:UIControlStateNormal];
        _hideHeight = hideHeight;
    }
    [_tableView reloadData];
}

- (IBAction)editAddrButton:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    _addrDic = _addrList[indexPath.row];
    isEdit = YES;
    [self performSegueWithIdentifier:@"addAddrSegue" sender:nil];
}

- (IBAction)deleteAddrButton:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (![_addrList[indexPath.row][@"id"] isEqual:[NSNull null]]) {
        NSInteger addrId = [_addrList[indexPath.row][@"id"] integerValue];
        [self deleteAddr:addrId];
    }
}

- (IBAction)addAddrButtonPressed:(UIButton *)sender {
    isEdit = NO;
    [self performSegueWithIdentifier:@"addAddrSegue" sender:nil];
}

- (IBAction)closeButtonPressed:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)setDefaultButtonPressed:(UIButton *)sender {
    UIView *superView = sender.superview;
    while (![superView isKindOfClass:[UITableViewCell class]]) {
        superView = superView.superview;
    }
    UITableViewCell *cell = (UITableViewCell *)superView;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (![_addrList[indexPath.row][@"id"] isEqual:[NSNull null]]) {
        NSInteger addrId = [_addrList[indexPath.row][@"id"] integerValue];
        [self setDefaultAddr:addrId];
    }
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"addAddrSegue"]) {
        BDAddrAddTableTableViewController *vc = (BDAddrAddTableTableViewController *)segue.destinationViewController;
        vc.userAddr = isEdit ? _addrDic : nil;
    }
}


@end
